<template>
  <div class="full-height">
    <div>
      <select-sport-type></select-sport-type>
    </div>
    <div class="row">
      <div class="col-12">
        <!-- 头部搜索条件区域 -->
        <div id="match-resource-query" class="full-width">
      
          <data-source-code @change="queryform_form_dataSourceCode_change" :show_toggle="true"></data-source-code>
          <div
            class="row q-px-md line-height-30px items-center q-gutter-x-lg bg-panda-dark-dark text-panda-text-dark"
          >
            <q-select
              filled
              rounded
              color="panda-text-light"
              bg-color="panda-light-light"
              style="width: 160px;"
              v-model="queryform_form.tournamentLevel"
              hide-bottom-space
              :options="match_level_constant"
              emit-value
              map-options
              dense
              options-dense
              popup-content-class="bg-panda-light-light text-panda-text-light"
            >
              <template v-slot:before>
                <span class="text-panda-text-dark">联赛等级</span>
              </template>
            </q-select>
            <q-select
              filled
              rounded
              color="panda-text-light"
              bg-color="panda-light-light"
              style="    width: 160px; "
              v-model="queryform_form.tournamentManagerIdStatus"
              :options="tournamentManagerIdStatus_arr"
              dense
              options-dense
              emit-value
              map-options
              option-value="value"
              option-label="label"
              popup-content-class="bg-panda-light-light text-panda-text-light"
            >
              <template v-slot:before>
                <span class="text-panda-text-dark">联赛ID状态</span>
              </template>
            </q-select>
            <q-select
              filled
              rounded
              color="panda-text-light"
              bg-color="panda-light-light"
              style="   min-width: 200px; max-width:300px;"
              v-model="queryform_form.sportRegionId"
              :options="sport_region_constant_filtered"
              dense
              clearable
              use-input
              options-dense
              emit-value
              map-options
              option-value="id"
              option-label="introduction"
              @filter="filterFn_sport_region_constant"
              popup-content-class="bg-panda-light-light text-panda-text-light"
            >
              <template v-slot:before>
                <span class="text-panda-text-dark">区域</span>
              </template>
            </q-select>
            <q-input
              filled
              rounded
              color="panda-text-light"
              bg-color="panda-light-light"
              dense
              clearable
              class="text-panda-text-dark panda-input-dense"
              v-model.trim="queryform_form.fast_search"
              placeholder="输入联赛ID"
            >
              <template v-slot:prepend>
                <q-icon name="search" class="text-panda-text-dark" />
              </template>
            </q-input>
            <div>
              <span
                class="panda-btn-light-dense q-mr-sm"
                @click="tosearch_queryform()"
                style="width:54px;height: 22px;"
              >搜索</span>
              <span
                class="panda-btn-light-dense"
                @click="export_data()"
                style="width:54px;height: 22px;"
              >导出</span>
            </div>
            <q-space></q-space>
          </div>
          <div
            class="row q-px-md items-center q-gutter-x-sm line-height-30px bg-panda-light-light full-width"
            v-if="selected_item_pool.length>0"
          >
            <span class="panda-round-dot panda-dot-blue"></span>
            <span
              class="text-panda-text-light q-mr-lg"
              v-if="!show_associate_success"
            >共选中{{selected_item_pool.length}}条数据</span>
            <span class="text-panda-text-light q-mr-lg" v-if="show_associate_success">已关联成功</span>
            <q-btn
              v-if="selected_item_pool.length>1"
              class="panda-btn-dense panda-btn-light-dense"
              label="关联为同一联赛"
              @click="handle_associate_or_merge_match"
            />
            <q-btn
              class="panda-btn-dark-dense"
              :label="selected_item_pool.length==1?'关闭': '取消'"
              @click="handle_reset_selected_item_pool"
            />
            <q-space />
          </div>
          <div class="full-width">
            <!-- v-if="selected_item_pool.length>0" -->
            <q-table
              title
              :data="selected_item_pool"
              :columns="tablecolumns"
              dense
              row-key="name"
              class="bg-panda-dark-dark panda-table full-width"
              separator="cell"
              hide-bottom
              hide-header
              :pagination.sync="pagination"
            >
              <template v-slot:body="props">
                <tablerow
                  :props="props"
                  :is_top_slot="1"
                  :tablecolumns="tablecolumns"
                  class="text-panda-text-light"
                  :show_right_detail_obj="show_right_detail_obj"
                  @item_click="table_item_click"
                  @toggle_select="selected_table_items_change"
                ></tablerow>
              </template>
            </q-table>
          </div>
        </div>

        <!-- 正常列表格展示 -->
        <tableLoading :loading="tabledata_loading" />
        <q-table
          :title="tabletittle"
          :data="tabledata"
          :columns="tablecolumns"
          dense
          row-key="name"
          class="bg-panda-base-dark text-panda-text-light panda-table panda-sticky-header-table full-width"
          table-header-class="panda-table"
          :separator="separator"
          :pagination.sync="pagination"
          :no-data-label="data_label"
          :table-style="` max-height: ${scroll_area_height}px `"
        >
          <!-- :table-style="` max-height: ${scroll_area_height}px `" -->

          <!-- :loading="tabledata_loading" -->
          <!-- :pagination.sync="pagination" -->
          <!-- <template v-slot:header="props">
  <tableheader :props="props"  :tablecolumns='tablecolumns'></tableheader>
          </template>-->

          <!-- :table-style="{ backgroundColor: '#ff0000' }" -->

          <template v-slot:body="props">
            <tablerow
              :props="props"
              :is_top_slot="0"
              :tablecolumns="tablecolumns"
              :show_right_detail_obj="show_right_detail_obj"
              @init_tabledata="init_tabledata_force"
              @change_match_level="change_match_level"
              @table_item_click_expanded="table_item_click_expanded"
              @item_click="table_item_click"
              @toggle_select="selected_table_items_change"
            ></tablerow>
          </template>
          <template v-slot:bottom>
            <panda-pagination
              :total="total"
              :tabledata_can_request="tabledata_can_request"
              :queryform_form_changed="queryform_form_changed"
              @handle_currentPage_change="handle_currentPage_change"
              @init_tabledata="init_tabledata"
            ></panda-pagination>
          </template>
        </q-table>
      </div>
      <!-- 赛事编辑页面 -->
      <div
        class="fixed fixed-right bg-panda-base-dark panda-table border-left text-panda-text-light"
         v-if="showrightdetail"
        style="width:350px;  box-shadow: -1px 0 0 0 rgba(0,0,0,0.50);   top: 61px;  width: 350px; z-index:5"
        :style="right_component_style" 
      > <!--style="compute_left_component_style()"-->
        <right-info :right_detail_obj="show_right_detail_obj" @toedit="to_show_match_edit"></right-info>
      </div>
    </div>
  </div>
</template>
<style lang="stylus" scoped></style>
<script>
import { mapGetters, mapActions } from "vuex";
import { api_match } from "src/api/index.js";
import mixins from "src/mixins/index.js";

import matchmixin from "src/mixins/pages/match/match.js";
import selectedTableItemMixin from "src/mixins/pages/match/selectedTableItem.js";
import { match_resource_tabledata } from "src/mock/match/index.js";
import { tablecolumns_config } from "src/pages/match/resource/config/config.js";
import selectSportType from "src/components/query/selectSportType.vue";
import dataSourceCode from "src/components/query/dataSourceCode.vue";
import tableheader from "src/components/table/tableheader.vue";
import pandaPagination from "src/components/pagination/pagination.vue";
import breakwordsmixin from "src/mixins/style/breakwords.js";
import tablerow from "src/pages/match/resource/component/tablerow.vue";
import { dom } from "quasar";
import alert_component from "src/config/alert/match.js";
import tableLoading from "src/components/table/tableLoading.vue";
const { height, width } = dom;
export default {
  mixins: [
    ...mixins,
    matchmixin,
    selectedTableItemMixin,
    breakwordsmixin
  ],
  components: {
    rightInfo: () => import("src/pages/match/resource/component/rightInfo.vue"),
    matchEdit: () => import("src/pages/match/resource/component/matchEdit.vue"),
    miniMatchList: () =>
      import("src/pages/match/resource/component/miniMatchList.vue"),
    selectSportType,
    dataSourceCode,
    tableheader,
    pandaPagination,
    tablerow,
    tableLoading
  },
  data() {
    return {
      tabledata_loading: false,
      queryform_form: {},
      queryform_module: {
        dataSourceCode: [],
        dataSourceCode_all: true,
        sportRegionId: "",
        tournamentLevel: "",
        tournamentManagerId: "",
        tournamentManagerIdStatus: "",
        tournamentName: "",
        fast_search: ""
      },
      tournamentManagerIdStatus_arr: [
        { label: "全部", value: "" },
        { label: "有联赛ID", value: "1" },
        { label: "无联赛ID", value: "0" }
      ],
      sport_region_constant_filtered: [
        {
          id: "",
          introduction: "全部"
        }
      ],
      tabletittle: "",
      show_right_detail: false,
      show_right_detail_obj: {},
      scroll_area_height: "",
      level_change_pool: [],
      tablecolumns: tablecolumns_config,
      tabledata: [],
      showrightdetail_before_edit: "",
      id: ""
    };
  },
  created() {
    this.tablecolumns = this.rebuild_tablecolumns_config(this.tablecolumns);
  },

  methods: {
    init_tabledata_force(){
   this. init_tabledata_()

    },
    init_tabledata_(){
         this.init_tabledata_before();
      let params = this.compute_init_tabledata_params();
      params = this.delete_empty_property_with_exclude(params);
      console.log(this.api_model_name);
      api_match
        .post_tournament_queryTour(params)
        .then(res => {
        
          this.init_tabledata_after();
          let currentPage =
            this.find_value_in_obj_bypath(res, "res.data.data.page") * 1 || 1;
          //  核对返回值  是否是 用户请求页面
          console.log(this.currentPage);
          console.log(currentPage);

          if (this.currentPage == currentPage) {
            // 是
            let arr =
              this.find_value_in_obj_bypath(res, "res.data.data.records") || [];
            this.tabledata = this.rebuild_tabledata_to_needed(arr);
            this.table_item_click(arr[0]);
            this.currentPage = currentPage;
            this.request_currentPage = currentPage;

            this.total =
              this.find_value_in_obj_bypath(res, "res.data.data.total") * 1 ||
              0;
            this.compute_pagination();
            this.$forceUpdate();
          } else {
            // 否
            this. init_tabledata_()
          }
        });
    },
    init_tabledata() {
      console.log("表格请求时候的 this.pagination ");
      if (
        this.request_currentPage == this.currentPage &&
        this.currentPage != 1
      ) {
        return false;
      }
      console.log(this.pagination);
     this. init_tabledata_()
    },

    rebuild_tabledata_to_needed(arr) {
      arr.map((x, xi) => {
        x.show_level_change = false;
        x.show_expand = false;
        x.index = xi;
        if (this.selected_item_pool_id_all.includes(x.id)) {
          x.is_selected = true;
        } else {
          x.is_selected = false;
        }

        // 挂载 和自身关联的 数据商
        if (x.standard) {
          let codearr = [];
          x.relatedTour = x.relatedTour || [];
          x.relatedTour.map(y => {
            codearr.push(y.dataSourceCode);
            y.parent_id = x.id;
            y.parent_dataSourceCode = x.dataSourceCode;
          });
          x.all_related_dataSourceCode = Array.from(new Set(codearr));
        } else {
          x.all_related_dataSourceCode = [x.dataSourceCode];
        }
        // let str = "熊猫".repeat(50);
        // x.tournamentName = {
        //   en: str,
        //   zh: str,
        //   zs: str
        // };
      });
      console.log("加工后的列表数据");
      console.log(arr);
      return arr;
    },
    compute_init_tabledata_params() {
      let params = {
         sportId:this.sportId,
        dataSourceCode: this.queryform_form.dataSourceCode,
        page: this.currentPage,
        // page: 1,
        size: this.pageSize,
        sportRegionId: this.queryform_form.sportRegionId,
        tournamentLevel: this.queryform_form.tournamentLevel,
        tournamentManagerIdStatus: this.queryform_form.tournamentManagerIdStatus
      };
      if (this.queryform_form.dataSourceCode_all) {
        delete params.dataSourceCode;
      }
      if (Number(this.queryform_form.fast_search) > 0) {
        params.tournamentManagerId = this.queryform_form.fast_search;
      } else {
        // params.tournamentName = this.queryform_form.fast_search;
      }
      console.log(params);

      return params;
    },

    compute_scrollarea_style() {
      let hs = this.window_size_info.height - 36 - 30 - 60 - 44;
      let hq = height(document.getElementById("match-resource-query"));
      this.scroll_area_height = hs - hq + 30.84;
    },

    export_data() {
      let params = this.compute_init_tabledata_params();
      //  export const post_tournament_export = (params, url="/football/tournament/export") => axios.post(`${prefix}${url}`, params)
      // export const post_tournament_export = (params, url="/football/tournament/exportGet") => axios.get(`${prefix}${url}`, { params: { ...params } })
      api_match.post_tournament_export(params);
    },

    change_match_level(item) {
      //  v-if="!props.row.show_level_change"
      if (!item.show_level_change) {
        // 未显示，先重置池子在推入
        this.level_change_pool.map(x => {
          x.show_level_change = false;
        });
        this.level_change_pool = [];
        item.show_level_change = true;
        this.level_change_pool.push(item);
      } else {
        //已显示，已存入池子，先重置
        this.level_change_pool.map(x => {
          x.show_level_change = false;
        });
        this.level_change_pool = [];
      }
    },

    table_item_click(item) {
      console.log(" table_item_click(item)");
      console.log(item);
      this.show_right_detail_obj = this.$lodash.cloneDeep(item);
      this.show_right_detail = true;
    },
    queryform_form_dataSourceCode_change(val) {
      console.log(val);
      this.queryform_form.dataSourceCode = val.dataSourceCode;
      this.queryform_form.dataSourceCode_all = val.dataSourceCode_all;
    },

    to_show_match_edit(item) {
      this.$router.push({
        name: "match_resource_edit",
        query: {
          editing_obj_id: item.id
        }
      });
    },
    handle_associate_match() {
      if (
        this.selected_item_standard_arr.length +
          this.selected_item_unstandard_arr.length ==
        1
      ) {
        // 单条 数据 提升标准
        this.handle_associate_match_onOk();
      } else {
        let message = "";
        message = alert_component.Association_carry_on();

        this.begin_script_dialog_process(
          message,
          this.handle_associate_match_onOk
        );
      }
    },

    handle_associate_match_onOk() {
      // 必须 有两条数据 商
      // 单条  BC 可以直接 通过生成联赛ID 直接 两次调用 生成 标准联赛 并生成联赛ID
      let params = {
        sourceId: [],
        standardId: ""
      };
      if (this.selected_item_standard_arr[0]) {
        params.standardId = this.selected_item_standard_arr[0]["id"];
      }
      this.selected_item_unstandard_arr.map(x => {
        params.sourceId.push(x.id);
      });
      api_match
        .post_tournament_associate(params)
        .then(res => {
          let code = this.$lodash.get(res, "data.code");
          if (code == 200) {
            let data = this.$lodash.get(res, "data.data.records")[0];
            this.handle_dialog_onOk_callback_success(
              alert_component.success,
              () => {
                // 关联成功
                console.log(data);

                this.selected_item_pool_rebase();
                let arr = this.rebuild_tabledata_to_needed([data]);
                data = arr[0];
                data.is_selected = true;
                this.show_associate_success = true;
                this.selected_table_items_change(data);
                this.init_tabledata_force();
              }
            );
          } else {
            this.handle_dialog_onOk_callback_error(alert_component.failure); // 关联失败
            this.alert_message(res);
          }
        });
    },
    handle_merge_match() {
      // 必须两条 标准赛事 均有 是标准 联赛 均有 标准ID
      let message = alert_component.Association_carry_on();
      this.begin_script_dialog_process(message, this.handle_merge_match_onOk);
    },
    handle_merge_match_onOk() {
      let params = {
        standardSportTournamentIds: []
      };
      this.selected_item_standard_arr.map(x => {
        params.standardSportTournamentIds.push(x.id);
      });
      api_match.post_tournament_merge(params).then(res => {
        let code = this.$lodash.get(res, "data.code");
        if (code == 200) {
          let data = this.$lodash.get(res, "data.data.records")[0];
          console.log(data);
          this.handle_dialog_onOk_callback_success(
            alert_component.merge_success,
            () => {
              console.log(data);
              this.selected_item_pool_rebase();
              let arr = this.rebuild_tabledata_to_needed([data]);
              data = arr[0];
              data.is_selected = true;
              this.show_associate_success = true;
              this.selected_table_items_change(data);
              this.init_tabledata_force();
            }
          );
        } else {
          this.handle_dialog_onOk_callback_error(alert_component.merge_failure);
          this.alert_message(res);
        }
      });
    }
  }
};
</script>
